package com.shu.qq.config.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shu.qq.config.security.jwt.JwtTokenUtil;
import com.shu.qq.data.entity.User;
import com.shu.qq.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserService userService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account",account);
        User user = userService.getOne(userQueryWrapper);
        if (user == null){
            throw new UsernameNotFoundException("登录账号：[" + account + "]不存在");
        }
        String rolesStr = user.getRoles();

        user.setAuthorities(jwtTokenUtil.strArrayToAuthorityList(rolesStr));
        log.info("正在登录的用户为 {}",user.getAccount());
        return user;
    }

}
